package com.cloudspace.jindun.manager;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.dao.LoginUser;
import com.cloudspace.jindun.dao.LoginUserDao;
import com.cloudspace.jindun.model.User;
import com.cloudspace.jindun.utils.ObjUtil;

/**
 * Created by zengxianhua on 16/12/22.
 */

public class UserManager {
    private static UserManager instance;

    public synchronized static UserManager getInstance(){
        if (instance == null){
            instance = new UserManager();
        }

        return instance;
    }

    public  void addLoginUser(LoginUser record){
        if (JindunApp.getInstance().getDaoSession() == null) {
            return;
        }

        deleteAll();
        JindunApp.getInstance().getDaoSession().getLoginUserDao().insertOrReplace(record);
    }

    public void addLoginUser(User.UserData bean){
        if (ObjUtil.isEmpty(bean)){
            return;
        }

        LoginUser user = User.UserData.generateDatabean(bean);
        if (ObjUtil.isEmpty(user)){
            return;
        }

        addLoginUser(user);

    }

    public void deleteAll(){
        if (JindunApp.getInstance().getDaoSession() == null) {
            return;
        }

        JindunApp.getInstance().getDaoSession().getLoginUserDao().deleteAll();
    }

    public  void deleteLoginUser(String userId){
        if (JindunApp.getInstance().getDaoSession() == null) {
            return;
        }

        LoginUser user = JindunApp.getInstance().getDaoSession().getLoginUserDao().queryBuilder().where(LoginUserDao.Properties.UserId.eq(userId)).unique();

        if (ObjUtil.isEmpty(user)){
            return;
        }

        JindunApp.getInstance().getDaoSession().getLoginUserDao().delete(user);
    }

    public LoginUser queryLoginUser(){
        if (JindunApp.getInstance().getDaoSession() == null) {
            return null;
        }

        LoginUser user = JindunApp.getInstance().getDaoSession().getLoginUserDao().queryBuilder().unique();
        return user;
    }


    public User.UserData queryUserDataBean(){
        if (JindunApp.getInstance().getDaoSession() == null) {
            return null;
        }

        LoginUser user = JindunApp.getInstance().getDaoSession().getLoginUserDao().queryBuilder().unique();

        return User.UserData.generateDatabean(user);
    }

    public static void updateUserInfo(LoginUser result) {
        if (instance != null){
            instance.deleteAll();
            instance.addLoginUser(result);
        }
    }

}
